/**
 * Created by shenc on 2015/12/4.
 */
//var TOOLS_DEBUG=true;
var TOOLS_DEBUG=false;
var Global={
    areaData:null
};

//图片延时加载 img.lazy
//<img class="lazy" data-original="img/example.jpg" width="765" height="574">
$("img.lazy").lazyload({
    data_attribute  : "src",
    threshold : 200,        //提前加载阈值 200像素
    effect : "fadeIn",      //图片显示效果
    placeholder:'/images/blank.gif',
    load:function(elements_left, settings){
        //图片加载回掉函数
        $(this).removeClass('img-lazyload');
    }
});

//tab事件
$('.bl-tab').each(function(){
    $(this).simTab();
});

//tab事件
$('.bl-ddmenu').sSelect();

//数字输入插件
function numPlugin(obj, cb) {
    var that = obj;
    if (typeof that == 'undefined' || that.length == 0) return;

    var lBtn = that.find('.l-btn'),
        rBtn = that.find('.r-btn'),
        numInput = that.find('.num-input'),
        defVal = numInput.val(),
        curVal = defVal*1,
        min = (numInput.attr('min')||0)*1,
        max = (numInput.attr('max')||999)*1;

    //设置初始按钮状态
    setBtnStatus(curVal);

    lBtn.click(function () {
        if (curVal <= min) return;
        curVal--;
        setVal(curVal);
    });

    rBtn.click(function () {
        if (curVal >= max) return;
        curVal++;
        setVal(curVal);
    });

    numInput.blur(function () {
        max = numInput.attr('max');

        var blurVal = numInput.val();
        if (blurVal * 1 < min) {
            curVal = min;
        }
        if (blurVal * 1 > max) {
            curVal = max;
        }

        setVal(curVal);
    });
    numInput.on('input change', function () {
        curVal=parseInt(numInput.val())||1;
        setBtnStatus(curVal);//设置按钮状态

    });

    function setVal(val) {
        numInput.val(val * 1);//赋值
        setBtnStatus(val * 1);//设置按钮状态

        if (typeof cb == 'function') {
            cb(val, numInput);
        }
    }

    function setBtnStatus(val){

        //设置 '-' 按钮
        if(val<=min){
            //禁用 '-' 按钮
            lBtn.addClass('disabled').prop('disabled',true);

        }else{
            //启用 '-' 按钮
            lBtn.removeClass('disabled').prop('disabled',false);

        }

        //设置 '+' 按钮
        if(val>=max){
            //禁用 '+' 按钮
            rBtn.addClass('disabled').prop('disabled',true);

        }else{
            //启用 '+' 按钮
            rBtn.removeClass('disabled').prop('disabled',false);

        }
    }
}
//$('.num-tool').each(function(){
//    numPlugin($(this), function(){});
//});

//列表选择操作
function ListSelect(config) {

    var def = {
        viewBox: ".js-viewBox",
        jqP: "#listSelect",
        listEl: ".list-item",
        toolEl: ".js-tools",
        initStatus:'checked',
        url: "../js/test.json",
        callBacks: {
            oneSelCb: function (listItem, isSel, id) {
            },
            allSelCb: function (listItems, isSel, ids) {
            },
            delCb: function (listItem, id) {
            }
        }
    };


    this.opts = $.extend(true, def, config);
    this.jqP= $(this.opts.jqP);
    this.viewBoxEl = $(this.opts.viewBox);
    this.selectAll = this.jqP.find(".js-selectAll");
    this.selectOneList = this.jqP.find(".js-selectOneList");
    this.listEl = this.opts.listEl ? $(this.opts.listEl) : this.viewBoxEl.find(".list-item");
    this.toolEl = this.opts.toolEl ? $(this.opts.toolEl) : this.viewBoxEl.find(".js-tools");
    this.liLen = this.listEl.not('.disabled-item').length;
    this.selectNum = this.listEl.filter('.selected').length;
    this.init();
}
ListSelect.prototype = {
    constructor: ListSelect,
    init: function () {
        var This = this;

        //初始化checkbox状态
        if(This.opts.initStatus){
            This.selectAll.prop('checked',true);
            This.selectOneList.prop('checked',true);
            this.listEl.not('.disabled-item').addClass('selected').find('.js-checkbox').prop('checked',true);
        }else{
            This.selectAll.prop('checked',false);
            This.selectOneList.prop('checked',false);
            this.listEl.not('.disabled-item').removeClass('selected').find('.js-checkbox').prop('checked',false);
        }

        //单选选择
        this.listEl.on("click", ".js-checkbox", function () {
            var $this = $(this);
            This.selectFun($this.closest(This.opts.listEl));
        });

        //全选
        this.jqP.on("click", ".js-selectAll", function () {
            This.selectMultiple($(this));
        });

        //反选
        this.viewBoxEl.on("click", ".js-selectReverse", function () {
            This.selectReverseFun();
        });

        //全选一组
        this.viewBoxEl.on('click','.js-selectOneList',function(){
            This.selectOneListFun($(this));
        });

        //删除
        this.jqP.on("click", '.js-del', function (e) {
            e.preventDefault();
            This.delFun($(this));
        });

    },

    reinit:function(){
        this.jqP= $(this.opts.jqP);
        this.viewBoxEl = $(this.opts.viewBox);
        this.selectAll = this.jqP.find(".js-selectAll");
        this.selectOneList = this.jqP.find(".js-selectOneList");
        this.listEl = this.opts.listEl ? $(this.opts.listEl) : this.viewBoxEl.find(".list-item");
        this.toolEl = this.opts.toolEl ? $(this.opts.toolEl) : this.viewBoxEl.find(".js-tools");
        this.liLen = this.listEl.not('.disabled-item').length;
        this.selectNum = this.listEl.filter('.selected').length;
    },

    selectOneListFun:function($el){
        var viewList=$el.closest(this.opts.viewBox),
            liItem=viewList.find(this.opts.listEl).not('.disabled-item'),
            curLiLen=liItem.length,
            curSelLen=liItem.filter('.selected').length;

        if ($el.prop('checked')) {
            liItem.addClass("selected").find('.js-checkbox').prop('checked', true);
            this.selectNum = this.selectNum+curLiLen-curSelLen;
        } else {
            liItem.removeClass("selected").find('.js-checkbox').prop('checked', false);
            this.selectNum = this.selectNum-curSelLen;
        }

        if (this.selectNum == this.liLen) {
            this.selectAll.prop('checked', true);
            this.selectOneList.prop('checked', true);
        } else {
            this.selectAll.prop('checked', false);
        }

        if (typeof this.opts.callBacks.oneSelCb == "function") {
            this.opts.callBacks.oneSelCb();
        }
    },

    selectFun: function ($el) {
        if($el.hasClass('disabled-item')) return false;

        if ($el.hasClass("selected")) {
            $el.removeClass("selected");
            (this.selectNum > 0) ? this.selectNum-- : 0;
        } else {
            $el.addClass("selected");
            this.selectNum++;
        }
        if (this.selectNum > 0) {
            this.toolEl.addClass('has-select');

            if (this.selectNum == this.liLen) {
                this.selectAll.prop('checked', true);
                this.selectOneList.prop('checked', true);
            } else {
                this.selectAll.prop('checked', false);
                var curViewBox=$el.closest(this.opts.viewBox);
                var oneListLis=curViewBox.find(this.opts.listEl).not('.disabled-item');

                if(oneListLis.filter('.selected').length==oneListLis.length){
                    curViewBox.find('.js-selectOneList').prop('checked', true);
                }else{
                    curViewBox.find('.js-selectOneList').prop('checked', false);
                }

            }
        } else {
            this.reset();
            this.toolEl.removeClass('has-select');
        }


        if (typeof this.opts.callBacks.oneSelCb == "function") {
            this.opts.callBacks.oneSelCb();
        }
    },

    selectMultiple: function ($el) {

        if ($el.prop('checked')) {
            this.listEl.not('.disabled-item').addClass("selected").find('.js-checkbox').prop('checked', true);
            this.selectOneList.filter(function(){return !$(this).prop('disabled');}).prop('checked', true);
            this.selectNum = this.liLen;
        } else {
            this.reset();
        }

        if (this.selectNum > 0) {
            this.toolEl.addClass('has-select');
            this.selectAll.prop('checked', true);
        } else {
            this.toolEl.removeClass('has-select');
            this.selectAll.prop('checked', false);

        }

        if (typeof this.opts.callBacks.allSelCb == "function") {
            this.opts.callBacks.allSelCb();
        }
    },

    selectReverseFun: function () {
        var This = this;
        this.listEl.filter(".list-item").each(function () {
            This.selectFun($(this));
        });

        if (typeof this.opts.callBacks.allSelCb == "function") {
            this.opts.callBacks.allSelCb();
        }
    },

    getData: function () {
        return this.listEl.filter(".selected").not('.disabled-item').map(function () {
            return $(this).data("id");
        }).get().join(",");
    },

    getSelectLi: function () {
        return this.listEl.filter('.selected').not('.disabled-item');
    },

    delFun: function ($el, url) {
        var This = this,
            curType = $el.data("type"),
            id = (curType && curType == "all") ? (this.getData().length?this.getData().split(',') : []) : [$el.closest(".list-item").data("id")],
            postUrl = url || This.opts.url;
        var $removeEl = (curType && curType == "all") ? This.getSelectLi() : $el.closest(".list-item");

        if (id.length == 0) {
            layer.alert('至少选择一项！');
        } else {
            layer.confirm("确定要删除吗？", {title: '提示'}, function (index) {
                $el.addClass("disabled");
                $.ajax(postUrl, {
                        type: "delete",
                        dataType: 'json',
                        data: {goods_ids: id}
                    })
                    .done(function (res) {
                        if (res.message == "") {
                            $el.removeClass("disabled");

                            $removeEl.fadeOut(300, function () {
                                //删除后判断是否还有上下页
                                if($(this).siblings('.list-item').length==0){
                                    $(this).closest('.js-viewBox').remove();
                                }else{
                                    $(this).remove();
                                }

                                This.reinit();

                                if (!This.liLen) {
                                    window.location.reload();
                                }

                                if (typeof This.opts.callBacks.delCb == "function") {
                                    This.opts.callBacks.delCb();
                                }

                            });
                        } else {
                            $el.removeClass("disabled");
                        }

                        layer.close(index);
                    });
            });
        }

    },

    reset: function () {
        this.listEl.not('.disabled-item').removeClass("selected").find('.js-checkbox').prop('checked', false);
        this.selectOneList.prop('checked', false);
        this.selectNum = 0;
        this.toolEl.removeClass('has-select');
    },

    nextPage: function () {
        var $pagination = $(".bl-pagination"),
            $active = $pagination.find(".active"),
            nextHref = "";
        if ($active.length) {
            nextHref = $active.next("li").not(".disabled").find("a").attr("href") || $active.prev("li").not(".disabled").find("a").attr("href") || "";
        }
        return nextHref;
    }
};

//添加地址--获取数据
function getAreaData(initVal,cb,loading){
    var opts = {
        data: null,     // districtData为district-all.js中定义的变量
        defVal:initVal,
        selStyle: 'margin-left: 10px;',
        minWidth:80,
        fixWidth	: 0,
        select:  '#area',
        head		: '--请选择--',
        level		: 4,
        selClass	: '',		// 应用于自动创建的<select> class. 若初始化之前就存在的<select>会自动添加上
        loaderImg	: '../images/loading-1.gif'
    };

    if(Global.areaData){
        opts.data=Global.areaData;

        linkageSel = new LinkageSel(opts);
        opts = null; // 如果数据量大最好在创建LinkageSel实例之后清空
        loading&&loading.length&&loading.remove();
        linkageSel.onChange(function() {
            typeof cb=='function'&&cb(this);
        });
    }else{
        //加载数据
        $.ajax({
            url:'/area',
            type:'get',
            dataType:'json',
            success:function(res){
                //转换数据
                var linkageData={};
                var level2=[],level3=[],level4=[];

                //第1级数据
                for(var i=0;i<res.length;i++){
                    var curData=res[i];

                    if(curData.parent_code*1==0){
                        linkageData[curData.code]={name:curData.name};
                    }else{
                        level2.push(curData);
                    }

                }

                //第2级数据
                for(var ii=0;ii<level2.length;ii++){
                    var curData2=level2[ii];

                    if(typeof linkageData[curData2.parent_code] != 'undefined'){
                        if(typeof linkageData[curData2.parent_code].cell == 'undefined'){
                            linkageData[curData2.parent_code].cell={};
                        }

                        linkageData[curData2.parent_code].cell[curData2.code]={name:curData2.name};
                    }else{
                        level3.push(curData2);
                    }
                }

                //第3级数据
                for(var iii=0;iii<level3.length;iii++){
                    var curData3=level3[iii];

                    for(var p in linkageData){
                        if(linkageData.hasOwnProperty(p)){
                            var obj=linkageData[p].cell;

                            if(typeof obj != 'undefined' && typeof obj[curData3.parent_code] != 'undefined'){
                                if(typeof obj[curData3.parent_code].cell == 'undefined'){
                                    obj[curData3.parent_code].cell={};
                                }

                                obj[curData3.parent_code].cell[curData3.code]={name:curData3.name};
                                level4.push(curData3);//todo del
                                break;
                            }
                        }

                    }
                    //end inner for

                }
                //end out for

                //todo delete
                for(var j=0;j<level4.length;j++){

                    for(var jj=0;jj<level3.length;jj++){
                        if(level4[j].name==level3[jj].name){
                            level3.splice(jj,1);
                            break;
                        }
                    }
                }

                opts.data=linkageData;
                Global.areaData=linkageData;

                linkageSel = new LinkageSel(opts);
                opts = null; // 如果数据量大最好在创建LinkageSel实例之后清空
                loading&&loading.length&&loading.remove();

                linkageSel.onChange(function() {
                    typeof cb=='function'&&cb(this);
                });
            }
        });
    }

}

//模拟placeholder
$("[placeholder]").labelPlaceholder();

//搜索自动提示
var autocomplete=$('.js-autocomplete');
autocomplete.each(function(){
    var that=$(this);
    that.autocomplete({
        serviceUrl: that.data('url'),
        dataType:'json',
        deferRequestBy:100,
        lookupLimit:10,
        paramName:'keyword',
        triggerSelectOnValidInput:false,//true--当有完整匹配时隐藏列表
        lookupFilter: function (suggestion, originalQuery, queryLowerCase) {
            return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
        },
        formatResult:function(suggestion, currentValue){

            var result='',pattern = '(' + tools.escapeRegExChars(currentValue) + ')';

            result=suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
            result=result+'<span class="fn-fr f-size-S text-color-7 small">约'+suggestion.count+'个商品</span>';

            return result;
        },
        transformResult: function(response) {
            var result=[];

            for(var i=0;i<response.length;i++){
                result.push({"value":response[i].keyword+'',"count":response[i].count});
            }

            return {suggestions:result};
        },
        onSelect: function (suggestion) {
            that.closest('form').submit();
        }
    });
});


//加入收藏按钮
$(".J-add-collection").on('click',function(e){

    var btn = $(e.currentTarget);
    var reference_id = btn.attr('reference_id') || btn.data('id') ;
    var type = btn.attr('collection-type') || btn.data('type');

    //SHOP | GOODS
    $.ajax({
        url:'/my/collection',
        type:'POST',
        data:{'type':type,'reference_id':reference_id},
        dataType:'json',
        success:function(response){
            if (response.success==1){
                if(btn.hasClass('text-btn')){
                    btn.text('已收藏').off('click');
                    btn.removeClass('btn-primary').addClass('bg-success');
                }else{
                    btn.html('<i class="icon icon-fav"></i>已收藏').off('click');
                }


            }else{



            }
        }
    });


});

//猜你喜欢切换
var recommend=$('.js-recommend');
recommend.on('click','.js-reloadBtn',function(){
    var that=$(this),
        list=$('.js-recList'),
        listWrap=list.closest('.list-body'),
        liH=list.find('li').eq(0).height(),
        listH=list.height(),
        curStep,
        step=parseInt(listH/liH);

    listWrap.css('height',liH);
    curStep=that.data('step')||0;

    if(curStep>=step-1){
        list.css({'top':0});
        that.data('step',0);
    }else{
        step=curStep+1;
        list.css({'top':'-'+step*liH+'px'});
        that.data('step',step);
    }

    //fix bug lazyload.
    $(window).trigger('scroll');

});

//通用加入购物车
$('.J-add-cart').on('click',function(e){
    var that=$(this),id=that.data('id'),num= 1,goCart=that.data('gocart');
    var allCartItem=$('.js-cart').find('.cart-num');

    if(typeof id=='undefined'||id==''||that.hasClass('disabled')||that.prop('disabled')) return false;
    that.addClass('disabled').prop('disabled',true);

    $.ajax({
        url:'/cart',
        type:'post',
        dataType:'json',
        data:{goods_id:id,goods_num:num},
        success:function(res){
            if (typeof res.goods_num!='undefined' && res.goods_num != ''){
                typeof layer!='undefined'&&layer.msg('已加入购物车',{
                    icon: 1,
                    offset:'10px',
                    time:2000
                });
                allCartItem.text(res.goods_num);
                if(goCart) window.location.href='/cart';//如果按钮带data="goCart"属性，成功后跳转到购物车
            } else if(typeof res.message!='undefined' && res.message != ''){
                typeof layer!='undefined'&&layer.alert(res.message);
            } else{
                typeof layer!='undefined'&&layer.msg('操作失败，请刷新页面重试！',{offset:'10px'});
            }
            that.removeClass('disabled').prop('disabled',false);
        }
    });

});
